var app = getApp();
//城市选择
var area = require('../../utils/area.js')

var areaInfo = [];//所有省市区县数据

var provinces = [];//省

var citys = [];//城市

var countys = [];//区县

var index = [0, 0, 0];

var cellId;

var t = 0;
var show = false;
var moveY = 200;

Page({
  data: {
    shengArr: [],//省级数组
    shengId: [],//省级id数组
    shiArr: [],//城市数组
    shiId: [],//城市id数组
    quArr: [],//区数组
    Province:'',
    shengIndex: 0,
    shiIndex: 0,
    quIndex: 0,
    mid: 0,
    sheng: 0,
    city: 0,
    area: 0,
    code: 0,
    cartId: 0,
    addrId:0,


    show: show,
    provinces: provinces,
    citys: citys,
    countys: countys,
    value: [0, 0, 0]
  },
  nameCheck:function(e){
    var names = e.detail.value
    if (names.length === 0) {
      wx.showToast({
        title: '请填写姓名',
        icon: 'none'
      })
    } else if (names.length>10){
      wx.showToast({
        title: '姓名不得超过10个字符',
        icon: 'none'
      })
    }
  },
  phoneCheck:function(e){
    var telphone = e.detail.value
    if (telphone.length === 0) {
      wx.showToast({
        title: '请填写手机号',
        icon: 'none'
      })
    }
    else if (!(/^1(3|4|5|7|8)\d{9}$/.test(telphone))) {
      wx.showToast({
        title: '手机号格式不正确',
        icon:'none'
      })
    }
  },
  address:function(e){
    var addresses = e.detail.value
    if (addresses.length === 0) {
      wx.showToast({
        title: '请填写地址',
        icon: 'none'
      })
    }
  },
  formSubmit: function (e) {
    var  that=this
    var adds = e.detail.value;
    //对手机号进行审核
    if (!(/^1(3|4|5|7|8)\d{9}$/.test(adds.phone))) {
        wx.showToast({
              title: '请填写正确的手机号',
              duration: 2000
            });
    
    } else {
      var cartId = this.data.cartId;
      wx.request({
        url: app.d.ceshiUrl + '/Api/Address/add_adds',
        data: {
          id: this.data.addrId,
          user_id: app.d.userId,
          receiver: adds.name,
          tel: adds.phone,
          sheng: (this.data.sheng ? this.data.sheng : this.data.ShengId),
          city: (this.data.city ? this.data.city : this.data.ShiId),
          quyu: (this.data.area ? this.data.area : this.data.QuId),
          adds: adds.address,
          code: this.data.code,
        },
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {// 设置请求的 header
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          // success
          var status = res.data.status;
          if (status == 1) {
            wx.showToast({
              title: '保存成功！',
              duration: 2000
            });
            setTimeout(function () {
              wx.redirectTo({
                url: 'user-address/user-address?cartId=' + cartId
              })
            }
              , 1000)
          } else {
   
              wx.showToast({
                title: res.data.err,
                duration: 2000,
                icon:'none'
              });
          }
        },
        fail: function () {
          wx.showToast({
            title: '网络不给力！',
            duration: 2000
          });
        }
      })
      this.setData({
        tel:adds.phone
      })
    }
  },
    //滑动事件
  bindChange: function (e) {
    var val = e.detail.value
     console.log(e)
    //判断滑动的是第几个column
    //若省份column做了滑动则定位到地级市和区县第一位
    if (index[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
      getCityArr(val[0], this);//获取地级市数据
      getCountyInfo(val[0], val[1], this);//获取区县数据
    } else {    //若省份column未做滑动，地级市做了滑动则定位区县第一位
      if (index[1] != val[1]) {
        val[2] = 0;
        getCountyInfo(val[0], val[1], this);//获取区县数据
      }
    }
    index = val;

    console.log(index + " => " + val);
    console.log(provinces[val[0]].id);
    console.log(citys[val[1]].id);
    console.log(countys[val[2]].id);
    //更新数据
    this.setData({
      value: [val[0], val[1], val[2]],
      provinceq: provinces[val[0]].name,
      cityq: citys[val[1]].name,
      countyq: countys[val[2]].name,
      sheng: provinces[val[0]].id,
      city: citys[val[1]].id,
      area: countys[val[2]].id
    })

  },
  onLoad: function (options) {
    var that = this;

        //获取省市区县数据
    area.getAreaInfo(function (arr) {
      areaInfo = arr;
      //获取省份数据
      getProvinceData(that);
    });

    if (app.globalData.froms == 'user') {
      wx.setNavigationBarColor({
        frontColor: 'white',
        backgroundColor: '#e93d3b',
      })
    } else {
      wx.setNavigationBarColor({
        frontColor: 'white',
        backgroundColor: '#e93d3b',
      })
    }

    if (options.cartId){
      that.setData({
        cartId: options.cartId
      })
      wx.request({
        url: app.d.ceshiUrl + '/Api/Address/get_province',
        data: {},
        method: 'POST',
        success: function (res) {
          var status = res.data.status;
          var province = res.data.list;
          var sArr = [];
          var sId = [];
          sArr.push('请选择');
          sId.push('0');
          for (var i = 0; i < province.length; i++) {
            sArr.push(province[i].name);
            sId.push(province[i].id);
          }
          that.setData({
            shengArr: sArr,
            shengId: sId
          })
        },
        fail: function () {
          wx.showToast({
            title: '网络不给力！',
            duration: 2000
          });
        },
      })
    } else if (options.addrId){
      this.setData({
        addrId: options.addrId 
      })
      wx.request({
        url: app.d.ceshiUrl + '/Api/address/get_address',
        data: {
          id: options.addrId,
          // user_id: app.d.userId,
        },
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {// 设置请求的 header
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          console.log(res.data.address)
          var adds = res.data.address

          // that.getProvince(adds.sheng)
          that.setData({  
            sheng: adds.sheng,
            city: adds.city,
            area: adds.quyu,
            provinceq: adds.sheng1,
            cityq: adds.city1,
            countyq: adds.quyu1,
            name: adds.name,
            tel: adds.tel,
            address:adds.address,
            code: adds.code
          })
        },
        fail: function () {
          wx.showToast({
            title: '网络不给力！',
            duration: 2000
          });
        }
      })
    }
  },
  onShareAppMessage: function () {
    return {
      title: '',
      path: '',
      success: function (res) {
        // 分享成功
      },
      fail: function (res) {
        // 分享失败
      }
    }
  },
    //移动按钮点击事件
  translate: function (e) {
    if (t == 0) {
      moveY = 0;
      show = false;
      t = 1;
    } else {
      moveY = 200;
      show = true;
      t = 0;
    }
    // this.animation.translate(arr[0], arr[1]).step();
    animationEvents(this,moveY, show);
    
  },
    //隐藏弹窗浮层
  hiddenFloatView(e){
    console.log(e);
    moveY = 200;
    show = true;
    t = 0;
    animationEvents(this,moveY, show);

  },

})
  //动画事件
function animationEvents(that,moveY,show){
  console.log("moveY:" + moveY + "\nshow:" + show);
  that.animation = wx.createAnimation({
    transformOrigin: "50% 50%",
    duration: 400,
    timingFunction: "ease",
    delay: 0
  }
  )
  that.animation.translateY(moveY + 'vh').step()

  that.setData({
    animation: that.animation.export(),
    show: show
  })
}
//获取省份数据
function getProvinceData(that) {
  var s;
  provinces = [];
  var num = 0;
  for (var i = 0; i < areaInfo.length; i++) {
    s = areaInfo[i];
    if (s.tid == "0") {
      provinces[num] = s;
      num++;
    }
  }
  that.setData({
    provinces: provinces
  })
console.log(provinces);
  //初始化调一次
  getCityArr(0, that);
  getCountyInfo(0, 0, that);
  that.setData({
    provinceq: "北京",
    cityq: "北京",
    countyq: "东城区",
    sheng: 1,
    city: 2,
    area: 3
  })

}

// 获取地级市数据
function getCityArr(count, that) {
  var c;
  citys = [];
  var num = 0;
  for (var i = 0; i < areaInfo.length; i++) {
    c = areaInfo[i];
    if (c.tid == provinces[count].id) {
      citys[num] = c;
      num++;
    }
  }
  if (citys.length == 0) {
    citys[0] = { name: '' };
  }

  that.setData({
    city: "",
    citys: citys,
    value: [count, 0, 0]
  })
}

// 获取区县数据
function getCountyInfo(column0, column1, that) {
  var c;
  countys = [];
  var num = 0;
  for (var i = 0; i < areaInfo.length; i++) {
    c = areaInfo[i];
    if (c.tid == citys[column1].id) {
      countys[num] = c;
      num++;
    }
  }
  if(countys.length == 0){
    countys[0] = {name:''};
  }
  that.setData({
    county: "",
    countys: countys,
    value: [column0, column1, 0]
  })
}
